package com.biao.hashmap;

import java.util.HashMap;

// 重写equals和hashcode方法，防止内存溢出
public class Demo02_Override_EqualsAndHashcode {
    // 设置堆空间：-Xmx3M  -Xms3M
    // 再测试
    public static void main(String[] args) {
        HashMap<TestKey, Integer> map = new HashMap<>();
        int counter = 0;
        while (true) {
            TestKey testKey = new TestKey("aBiu", "123456");
            map.put(testKey, 1);
            counter++;
            if (counter % 1000 == 0) {
                System.out.println("map size: " + map.size());
                System.out.println("运行" + counter + "次后，剩余内存" +
                        Runtime.getRuntime().freeMemory() / (1024 * 1024) + "MB");
            }
        }
    }
}

class TestKey {
    private final String id;
    private String name;

    public TestKey(String id, String name) {
        this.id = id;
        this.name = name;
    }

    public void setName(String name) {
        this.name = name;
    }

    @Override
    public int hashCode() {
        return super.hashCode();
    }

    @Override
    public boolean equals(Object obj) {
        if (obj instanceof TestKey) {
            return name.equals(((TestKey) obj).name) && id.equals(((TestKey) obj).id);
        } else {
            return false;
        }
    }
}